//
//  YCLoginUser.m
//  YCSchool
//
//  Created by gmall on 16/5/20.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCLoginUser.h"

NSString * const YCLoginUserInfoArchiverFileEncryptKey = @"694B756E376E502C";
NSString * const YCLoginUserInfoArchiverFileEncryptIV = @"24737776512A476C";
NSString * const YCLoginUserIMInfoEncryptKey = @"5e5a47364b49712a4d6c5576246163634d57555270714157"; //@"^ZG6KIq*MlUv$accMWURpqAW"
NSString * const YCLoginUserIMInfoEncryptIV = @"3252387459663575"; //@"2R8tYf5u"

/// 用户信息归档路径
//NSString * const YCLoginUserInfoArchiverFileName = @"userData.dat";

/// 更新用户信息结束时通知
NSString * const YCLoginUserUpdateInfoFinishedNotificationName = @"YCLoginUserUpdateInfoFinishedNotification";
/// 更新联系信息结束通知
NSString * const GOLoginUserUpdateContactInfoFinishedNotificationName = @"YCLoginUserUpdateContactInfoFinishedNotification";

static YCLoginUser *_LoginUserInstance = nil;

@implementation YCLoginUser

MJExtensionCodingImplementation
// 属性替换
+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
    return @{
                @"userId":@"uid",
                @"userToken":@"token",
                @"userNickname":@"nickname",
             };
}

// 这个数据中的属性会进行归档
//+ (NSArray *)mj_allowedPropertyNames
//{
//    return @[];
//}

// 忽略不需要归档的属性
+ (NSArray *)mj_ignoredCodingPropertyNames
{
    return @[
             @"isChange_netWork",
             @"isNetworking",
             @"isUpdateVersion",
             @"is_login",
             @"userBgimg",
             @"userAvatar"
             ];
}

/// 获取单例对象
//+ (instancetype)shareLoginUser
//{
//    if(!_LoginUserInstance)
//    {
//        NSString *filePath = [[UIApplication sharedApplication].yc_documentsPath stringByAppendingPathComponent:YCLoginUserInfoArchiverFileName];
//        // 解密
//        NSData *data = [[NSData dataWithContentsOfFile:filePath] yc_decryptWithKey:[YCLoginUserInfoArchiverFileEncryptKey yc_stringOfHexString]
//                                                                                iv:[YCLoginUserInfoArchiverFileEncryptIV yc_stringOfHexString]];
//        if(data)
//        {
//            _LoginUserInstance = [NSKeyedUnarchiver unarchiveObjectWithData:data];
//        }
//    }
//    return _LoginUserInstance;
//}

/// 根据用户名获取用户对象
+ (instancetype)loginUserWithName:(NSString *)userNickName
{
    NSString *filePath = [[UIApplication sharedApplication].yc_documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",userNickName]];
    if ([NSData dataWithContentsOfFile:filePath]) {
        // 解密
        NSData *data = [[NSData dataWithContentsOfFile:filePath] yc_decryptWithKey:[YCLoginUserInfoArchiverFileEncryptKey yc_stringOfHexString]
                                                                                iv:[YCLoginUserInfoArchiverFileEncryptIV yc_stringOfHexString]];
        if(data)
        {
            _LoginUserInstance = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
    } else {
        return nil;
    }
    return _LoginUserInstance;
}

/// 登录
+ (void)loginWithUser:(YCLoginUser *)user
{
    @synchronized(_LoginUserInstance)
    {
        NSString *filePath = [[UIApplication sharedApplication].yc_documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",user.userNickname]];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
        data = [data yc_encryptWithKey:[YCLoginUserInfoArchiverFileEncryptKey yc_stringOfHexString]
                                    iv:[YCLoginUserInfoArchiverFileEncryptIV yc_stringOfHexString]];
        if(data)
        {
            [data writeToFile:filePath atomically:YES];
            _LoginUserInstance = user;
        }
    }
}

/// 退出
- (void)loginOut
{
    @synchronized(_LoginUserInstance)
    {
        NSHTTPCookieStorage *store = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for(NSHTTPCookie *cookie in store.cookies)
        {
            [store deleteCookie:cookie];
        }
        NSString *filePath = [[UIApplication sharedApplication].yc_documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",_LoginUserInstance.userNickname]];
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        _LoginUserInstance = nil;
    }
}


- (NSString *)userSexString
{
    NSString *string = @"未设置";
    
    switch (self.userSex)
    {
        case YCUserSexBoy:
            string = @"男";
            break;
            
        case YCUserSexGril:
            string = @"女";
            break;
            
        case YCUserSexNoSetting:
        default:
            string = @"保密";
            break;
    }
    return string;
}

- (NSString *)userMarriageStatusString
{
    NSString *string = @"未设置";
    
    switch (self.userMarriageStatus)
    {
        case YCUserMarriageStatusMarried:
            string = @"已婚";
            break;
            
        case YCUserMarriageStatusSingle:
            string = @"单身";
            break;
            
        case YCUserMarriageStatusNoSetting:
        default:
            string = @"未设置";
            break;
    }
    return string;
}



/// 存储位置 用户id拼接
- (NSString *)homeDirectory
{
    NSString *dir = [LKDBUtils getDirectoryForDocuments:[NSString stringWithFormat:@"%zd",self.userId]];
    NSFileManager *fm = [NSFileManager defaultManager];
    if(![fm fileExistsAtPath:dir])
    {
        NSError *error;
        [fm createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:&error];
    }
    return dir;
}

/// 存储路径
- (NSString *)dbFilePath
{
    NSString *path = [self homeDirectory];
    path = [path stringByAppendingPathComponent:@"LKDB.db"];
    return path;
}

- (NSString *)ycschoolOpenID
{
    NSString *openId = [NSString stringWithFormat:@"ycschool_%@",[[NSString stringWithFormat:@"%zd",self.userId] yc_md5String]];
    return openId;
}


- (BOOL)is_login
{
    return YES;
}

@end
